package com.lee.nio.selector;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.charset.StandardCharsets;
import java.util.Iterator;
import java.util.Set;

/**
 * selector
 *
 * @author dralee
 * @date 2021-12-29 23:38:09
 **/
public class NIOServer {
    public static void main(String[] args) throws IOException {
        // 创建ServerSocketChannel -> ServerSocket
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        // 得到一个Selector对象
        Selector selector = Selector.open();
        // 绑定一个端口6666，在服务器端监听
        serverSocketChannel.socket().bind(new InetSocketAddress(6666));
        // 设置为非阻塞
        serverSocketChannel.configureBlocking(false);
        // 把serverSocketChannel注册到Selector关心事件为OP_ACCEPT
        serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
        System.out.println("注册后的selectionKey数量=" + selector.keys().size());
        // 等待客户端连接
        while (true) {
            if (selector.select(1000) == 0) { // 等待1秒，如没事情发生，返回
                System.out.println("服务等待了1秒，无连接");
                continue;
            }
            // 如果返回的>0，就获取相关的selectionKey集合
            // 1、如果返回>0，表示已经获取到关注事件
            // 2、selector.selectedKeys()返回关注事件集合
            // 通过selectionKeys反向获取通道
            Set<SelectionKey> selectionKeys = selector.selectedKeys();
            System.out.println("selectionKeys数量=" + selectionKeys.size());
            // 遍历Set<SelectionKey>，使用迭代器遍历
            Iterator<SelectionKey> keyIterator = selectionKeys.iterator();
            while (keyIterator.hasNext()) {
                // 获取SelectionKey
                SelectionKey key = keyIterator.next();
                // 根据key对应通道发生事件做相应处理
                if (key.isAcceptable()) { // 如果是OP_ACCEPT，有新客户端连接
                    // 为该客户端生成一个SokcetChannel
                    SocketChannel socketChannel = serverSocketChannel.accept();
                    System.out.println("客户端连接成功 生成了一个socketChannel " + socketChannel.hashCode());
                    // 将socketChannel设置为非阻塞
                    socketChannel.configureBlocking(false);
                    // 将socketChannel 注册到selector，关注事件为OP_READ,，同时给socketChannel
                    // 关联一个Buffer
                    socketChannel.register(selector, SelectionKey.OP_READ, ByteBuffer.allocate(1024));
                    System.out.println("客户端连接后，注册的selectionKey数量=" + selector.keys().size());
                } else if (key.isReadable()) { // 发生OP_READ
                    // 通过key反向获取对应channel
                    SocketChannel channel = (SocketChannel) key.channel();
                    // 获取到该channel关联的buffer
                    ByteBuffer buffer = (ByteBuffer) key.attachment();
                    channel.read(buffer);
                    System.out.println("from 客户端" + new String(buffer.array(), 0, buffer.position(), StandardCharsets.UTF_8));
                }

                // 手动从集合中移动当前selectionKey，防止重复操作
                selectionKeys.remove(key);
            }
        }
    }
}
